
package cz.cvut.fel.y36mm1.videostreaming;

import cz.cvut.fel.y36mm1.videostreaming.exceptions.ServerCannotBeClientException;
import cz.cvut.fel.y36mm1.videostreaming.client.*;
import cz.cvut.fel.y36mm1.videostreaming.exceptions.CannotConnectToServerException;
import cz.cvut.fel.y36mm1.videostreaming.exceptions.ClientCannotBeServerException;
import cz.cvut.fel.y36mm1.videostreaming.server.Server;
import javax.microedition.lcdui.Displayable;

/**
 * Objekt sidlici nad server/klient vlastnostmi zarizeni. Zajistuje, ze zarizeni
 * je v jeden okamzik pouze v jednom stavu.
 * @author Jiri Chadima, chadij1
 */
public class Device {

	public static final int RECEIVER = 1;
	public static final int BROADCASTER = 2;
	private int state = 0;
	private Client client = null;
	private Server server = null;
	private MainMidlet root;

	public Device(MainMidlet midlet) {
		root = midlet;
	}

	/**
	 * Start server.
	 * @return serverScreen
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.ClientCannotBeServerException if device is already marked as client
	 */
	public Displayable initiateServer() throws ClientCannotBeServerException {
		if(state == BROADCASTER) {throw new ClientCannotBeServerException();}
		state = RECEIVER;
		server = new Server(root.getCommander());
		return server.getServerScreen();
	}

	/**
	 * Stop server
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.ClientCannotBeServerException if device is already marked as client
	 */
	public void terminateServer() throws ClientCannotBeServerException {
		if(state == BROADCASTER) {throw new ClientCannotBeServerException();}
		server.terminate();
		state = 0;
		server = null;
	}

	/**
	 * Starts client and connection.
	 * @param serviceURL where to connect
	 * @return screen of client, it's showing camera
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.ServerCannotBeClientException
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.CannotConnectToServerException
	 */
	public Displayable initiateClient(String serviceURL) throws ServerCannotBeClientException, CannotConnectToServerException {
		if(state == RECEIVER) {throw new ServerCannotBeClientException();}
		state = BROADCASTER;
		client = new Client(serviceURL, root.getCommander());
		client.startConnection();
		return client.getVideoCanvas();
	}

	/**
	 * Stops client.
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.ServerCannotBeClientException
	 */
	public void terminateClient() throws ServerCannotBeClientException {
		if(state == RECEIVER) {throw new ServerCannotBeClientException();}
		client.terminateClient();
		state = 0;
		client = null;
	}

	public MainMidlet getMainMidlet() {
		return root;
	}

	/**
	 * just delegation to client
	 * @throws cz.cvut.fel.y36mm1.videostreaming.exceptions.ServerCannotBeClientException
	 */
	public void sendSnapshot() throws ServerCannotBeClientException {
		if(state == RECEIVER) {throw new ServerCannotBeClientException();}
		client.sendSnapshot();

	}

}
